#include "GMPingConnection.h"
#include "Factory.h"
#include "TimerMS.h"
#include "GMReturnPing.h"
#include "ClientManager.h"
#include "SendGameMessage.h"
#include "MessageQueue.h"

#include <iostream>

GMPingConnection::GMPingConnection()
{

}

void GMPingConnection::Execute()
{

}

bool GMPingConnection::Read(SocketMessage* sm)
{
	int tempTS = 0;
	sm->ReadInt(&tempTS);
	
	m_timeStamp = (unsigned int)(abs(tempTS));
	unsigned int latency = TheTimerMS::Instance()->GetTimeMS() - m_timeStamp;

	if (latency < 10000)
	{
		TheMsgQueue::Instance()->AddLagTime(latency);
		std::cout << "received time in ms: " << m_timeStamp << std::endl;
		std::cout << "current time in ms: " << TheTimerMS::Instance()->GetTimeMS() << std::endl;
		//TheTimerMS::Instance()->SetTimeMS(m_timeStamp);
		std::cout << "latency in ms: " << latency << std::endl;
	}
	else
	{
		latency = m_timeStamp - TheTimerMS::Instance()->GetTimeMS();
		TheMsgQueue::Instance()->AddLagTime(latency);
		std::cout << "Latency > 1000ms" << std::endl;
		std::cout << "Alt_Latency: " << latency << std::endl;
	}
	// send return ping
	GMReturnPing* gm = new GMReturnPing();
	gm->SetTimeStamp(m_timeStamp);
	SendGameMessage(*gm, &(TheClientManager::Instance()->GetSocket()));

	return true;
}

void GMPingConnection::Write(SocketMessage* sm)
{
	sm->WriteString("GMPingConnection");
	//TheTimerMS::Instance()->UpdateTime();
	m_timeStamp = TheTimerMS::Instance()->GetTimeMS();
	sm->WriteInt(m_timeStamp);
}